#!/usr/bin/env python
# -*- coding: utf-8 -*-
from my_app import db
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SelectField, FileField
from wtforms.validators import InputRequired,  ValidationError


class DataBaseConfig(db.Model):
    """数据库配置模型"""
    id = db.Column(db.Integer, primary_key=True)
    env = db.Column(db.String(255))
    host = db.Column(db.String(255))
    port = db.Column(db.Integer())
    username = db.Column(db.String(255))
    password = db.Column(db.String(255))
    database = db.Column(db.String(255))
    api_path = db.Column(db.String(255))
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))  # 定义模型的外键，id表示为关系
    user = db.relationship("User", backref=db.backref("databases", lazy="dynamic"))

    def __init__(self, env, host, port, username, password, database, api_path, user):
        self.env = env
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.database = database
        self.api_path = api_path
        self.user = user

    def __repr__(self):
        """将对象已字符串的形式表达出来"""
        return f"<DataBaseConfig {self.id}>"


def check_duplicate_env():
    """检查环境是否重复"""
    def _check_duplicate(form, field):
        res = DataBaseConfig.query.filter(DataBaseConfig.env == field.data).first()
        if res:
            raise ValidationError(f"{field.data} 环境已存在，请不要重复添加")
    return _check_duplicate


class DataBaseConfigForm(FlaskForm):
    """数据库配置表单"""
    env = StringField("Env", validators=[InputRequired()])
    host = StringField("Host", validators=[InputRequired()])
    port = IntegerField("Port", validators=[InputRequired()])
    username = StringField("UserName", validators=[InputRequired()])
    password = StringField("PassWord", validators=[InputRequired()])
    database = StringField("DataBase", validators=[InputRequired()])
    api_path = StringField("ApiPath", validators=[InputRequired()])


class CashValueForm(FlaskForm):
    """现价测试表单"""
    base_file = FileField("Base Cash", validators=[InputRequired()])


